package com.csb.service.impl;

import com.csb.config.MyConstants;
import com.csb.mapper.ApplyMapper;
import com.csb.mapper.AssetMapper;
import com.csb.pojo.Apply;
import com.csb.service.ApplyService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.interceptor.TransactionAspectSupport;

import java.util.List;

@Service
@Transactional
public class ApplyServiceImpl implements ApplyService {
    // 依赖
    @Autowired
    private ApplyMapper applyMapper;
    @Autowired
    private AssetMapper assetMapper;

    /**
     * 申请资产
     *
     * @param asIds
     * @param account
     * @return
     */
    @Override
    public boolean saveApplyInfo(String[] asIds, String account) {
        boolean flag = false;
        //根据资产编号去查询
        for (String asId : asIds) {
            //创建申请对象
            Apply apply = new Apply();
            //设置申请的资产编号
            apply.setAsId(asId);
            //设置申请者
            apply.setApplyer(account);
            try {
                // 向申请表插入一条数据
                applyMapper.saveApplyInfo(apply);
                // 回填该资产的状态位
                assetMapper.updateAsSetsAsState(asId, MyConstants.ASSET_ASSTATE_APPLYING);
                flag = true;
            } catch (Exception e) {
                e.printStackTrace();
                TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
                return false;
            }
        }
        return flag;
    }

    /**
     * 归还资产
     *
     * @param asIds
     * @param account
     * @return
     */
    @Override
    public boolean backApplyInfo(String[] asIds, String account) {
        boolean flag = false;
        //遍历asIds
        for (String asId : asIds) {
            //创建申请对象
            Apply apply = new Apply();
            //设置归还的资产编号
            apply.setAsId(asId);
            //设置归还者
            apply.setApplyer(account);
            //设置是否归还
            apply.setIsBack(MyConstants.BUSINESS_TYPE_BACK);
            try {
                // 向申请表插入一条数据
                applyMapper.saveApplyInfoBack(apply);
                // 回填该资产的状态位
                assetMapper.updateAsSetsAsState(asId, MyConstants.ASSET_ASSTATE_APPLYING);
                flag = true;
            } catch (Exception e) {
                e.printStackTrace();
                TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
                return false;
            }
        }
        return flag;
    }

    @Override
    public List<Apply> getPersonAppList(String account) {
        return applyMapper.getPersonAppList(account);
    }

    @Override
    @Cacheable(value = "appAllList", key = "'getPersonAppAllList'")
    public List<Apply> getPersonAppAllList() {
        return applyMapper.getPersonAppAllList();
    }

}
